跳到主要内容

Go 的网络测试

httptest

针对 http 开发的场景,使用标准库 net/http/httptest 进行测试更为高效。

假设需要测试某个 API 接口的 handler 能够正常工作,例如 helloHandler

func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}

编写测试用例

// test code
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)

func TestConn(t *testing.T) {
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
w := httptest.NewRecorder()

helloHandler(w, req) // 把这个测试请求传入

bytes, _ := ioutil.ReadAll(w.Result().Body)

if string(bytes) != "hello world" {
t.Fatal("expected hello world, but got", string(bytes))
}
}

这里可以直接使用提供的 httptest 包来测试 Handler 的执行结果